<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/29
 * Time: 18:42
 */

namespace Xcx\Model;

use Xcx\Controller\WxJsAPIController;

class GoodsOrderModel extends BaseModel
{

    /**
     * 获取确认订单详情
     * @param $orderNo
     * @return mixed
     */
    public function getConfirmOrderInfo($orderNo)
    {
        $order = $this->getOrderInfo($orderNo);
        $address = $this->getConfirmOrderAddress($order['addr_id']);
        $goodsList = $this->getOrderGoodsList($orderNo);
        $data['address'] = $address;
        $data['goods_list'] = $goodsList;
        $data['coupon'] = $this->getCoupon($order['total_fee']);
        $data['bargain'] = $this->getBargainInfo($orderNo);
        $order['freight'] = $this->getFreight($address,$goodsList);
        $data['order'] = $order;

        return $data;
    }

    /**
     * 获取订单信息
     * @param $orderNo
     * @return mixed
     */
    public function getOrderInfo($orderNo)
    {
        return $this->where(array('order_no'=>$orderNo))->find();
    }

    /**
     * 获取订单运费
     * @param $address
     * @param $goodsList
     * @return float|int
     */
    public function getFreight($address,$goodsList)
    {
        $freight = 0;
        if ($address) {
            $totalWeight = 0;
            foreach ($goodsList as $v) {
                $totalWeight += $v['weight'] * $v['count'];
            }
            $data = M('goods_freight')->where(array('province'=>$address['province']))->find();
            //查询运费是否特殊定价
            //如果没有特殊定价，则使用默认定价
            if (!$data) {
                $data = M('goods_freight')->where(array('id'=>'1'))->find();
            }
            //商品总重量小于首重
            if ($totalWeight <= $data['unit']) {
                $freight = $data['price'];
            } else {
                $overWeight = $totalWeight - $data['unit'];
                $freight = ceil($overWeight / $data['over_unit']) * $data['over_price'] + $data['price'];
            }
        }
        return $freight;
    }

    /**
     * 获取确认订单中的地址信息
     * @param $id
     * @return array|bool
     */
    private function getConfirmOrderAddress($id)
    {
        $Address = new AddressModel();
        $address = false;
        if ($id != null && $id != '') {
            $address = $Address->getAddressDetailsInfo($id);
            if (count($address) == 0) $address = false;
        }
        if (!$address) {
            $address = $Address->getDefaultAddress();
        }
        return $address;
    }

    /**
     * 获取订单商品列表
     * @param $orderNo
     * @return mixed
     */
    private function getOrderGoodsList($orderNo)
    {
        $OrderChild = new GoodsOrderChildModel();
        return $OrderChild->getOrderGoodsList($orderNo);
    }

    /**
     * 获取优惠券信息
     * @param $totalFee
     * @return bool
     */
    private function getCoupon($totalFee)
    {
        $Coupon = new UserCouponModel();
        return $Coupon->getDefaultCoupon($totalFee);
    }

    /**
     * 获取砍价信息
     * @param $orderNo
     * @return array|bool
     */
    private function getBargainInfo($orderNo)
    {
        $GoodsBargain = new GoodsBargainModel();
        $bargainCount = 0;
        $data['code'] = '1';//没有砍价权限
        $data['bargain_count'] =$bargainCount;
        if (!$GoodsBargain->checkBargainRight()) {
            $data = $GoodsBargain->getOrderBargainInfo($orderNo);
            if ($data) {
                $GoodsBargainDetails = new GoodsBargainDetailsModel();
                $bargainCount = $GoodsBargainDetails->getBargainCount($data['id']);
                $data['bargain_count'] =$bargainCount;
                $data['code'] = '3';//正在进行砍价
            } else {
                $data['code'] = '2';//有砍价权限
                $data['bargain_count'] =$bargainCount;
            }
        }
        return $data;
    }

    /**
     * 更新订单地址ID
     * @param $orderNo
     * @param $addrID
     * @return bool|false|int
     */
    public function updateOrderAddrID($orderNo,$addrID)
    {
        $res = $this->where(array('order_no'=>$orderNo,'uid'=>$this->uid))->data(array('addr_id'=>$addrID))->save();
        if ($res || $res == 0) return true;
        return false;
    }

    /**
     * 添加订单信息
     * @param $idList
     * @return bool|string
     */
    public function doAddOrder($idList)
    {
        //获取购物车选中商品详细信息
        $goodsList = $this->getConfirmGoodsList($idList);

        $orderNo = createOrderNO();
        $totalFee = 0;
        $childOrderArr = array();
        for ($i = 0; $i < count($goodsList); $i++) {
            $childOrder = array();
            $childOrder['order_no'] = $orderNo;
            $childOrder['gid'] = $goodsList[$i]['gid'];
            $childOrder['price'] = $goodsList[$i]['price'];
            $childOrder['count'] = $goodsList[$i]['count'];
            $childOrder['spec_id'] = $goodsList[$i]['spec_id'];
            $childOrder['add_time'] = time();
            $childOrderArr[] = $childOrder;
            $totalFee = $totalFee + $goodsList[$i]['price'] * $goodsList[$i]['count'];
        }

        //获取默认地址信息
        $Address = new AddressModel();
        $address = $Address->getDefaultAddress();

        $order['uid'] = $this->uid;
        $order['order_no'] = $orderNo;
        $order['total_fee'] = $totalFee;
        $order['freight'] = 0;
        if ($address) {
            $order['addr_id'] = $address['id'];
        }
        $order['add_time'] = time();

        M()->startTrans();
        $res1 = M('goods_order')->data($order)->add();
        $res2 = M('goods_order_child')->addAll($childOrderArr);

        if ($res1 && $res2) {
            M()->commit();
            return $orderNo;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 获取购物车选中商品详细信息
     * @param $idList
     * @return mixed
     */
    private function getConfirmGoodsList($idList)
    {
        $Cart = new CartModel();
        $list = $Cart->getConfirmGoodsList($idList);
        return $list;
    }

    /**
     * 发起支付
     * @param $orderNo
     * @param $type 1-优惠券；2-订单
     * @param $discountID
     * @param $addrID
     * @param $freight
     * @param $gid
     * @param $msg
     * @return bool|\Xcx\Controller\json数据，可直接填入js函数作为参数
     */
    public function pay($orderNo, $type, $discountID, $addrID, $freight, $gid, $msg)
    {
        M()->startTrans();
        //添加折扣信息
        $discountFee = 0;
        $res2 = $res3 = $res4 = $res5 = true;
        if ($type != 0) {
            $OrderDiscount = new GoodsOrderDiscountModel();
            $discountFee = $OrderDiscount->addOrderDiscount($orderNo, $type, $discountID);
            //处理优惠券/砍价状态
            $res4 = $this->dealDiscount($type, $discountID);
        }
        $Address = new GoodsOrderAddressModel();
        $res2 = $Address->addOrderAddress($orderNo, $addrID);

        //删除购物车
        $res5 = $this->dealCartList($orderNo);

        $order = $this->getOrderInfo($orderNo);
        //实际支付总价
        $payFee = $order['total_fee'] + $freight - $discountFee;

        $data['discount_fee'] = $discountFee;
        $data['freight'] = $freight;
        $data['pay_fee'] = $payFee;
        $data['msg'] = $msg;
        $data['state'] = 1;//修改订单状态为待支付

        $this->where(array('order_no'=>$orderNo))->data($data)->save();

        //商品信息
        $Goods = new GoodsModel();
        $goods = $Goods->getGoodsInfo($gid);

        if ($res2 && $res3 && $res4 && $res5) {
            M()->commit();
            $order['body'] = $goods['name'];
            $order['order_no'] = $orderNo;
            $order['price'] = $payFee;
            $WxJsAPI = new WxJsAPIController();
            return $WxJsAPI->pay($order);
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 删除购物车
     * @param $orderNo
     * @return mixed
     */
    private function dealCartList($orderNo)
    {
        $list = $this->getOrderGoodsList($orderNo);
        $idList = array_column($list,'gid');
        $specList = array_column($list,'spec_id');

        $Cart = new CartModel();
        return $Cart->deleteCartList($idList,$specList);
    }

    /**
     * 处理优惠券/砍价状态
     * @param $type
     * @param $discountID
     * @return bool
     */
    private function dealDiscount($type, $discountID) {
        if ($type == 0) return true;
        $state = 2;//2-完成；3-失效
        $res1 = true;
        if ($type == 1) {
            $state = 3;
            $UserCoupon = new UserCouponModel();
            $res1 = $UserCoupon->updateCouponState($discountID, 2);
        }
        $Bargain = new GoodsBargainModel();
        $res2 = $Bargain->updateBargainState($discountID, $state);
        if ($res1 && $res2) return true;
        return false;
    }

    /**
     * 重新支付
     * @param $orderNo
     * @return \Xcx\Controller\json数据，可直接填入js函数作为参数
     */
    public function rePay($orderNo)
    {
        $data = $this->where(array('order_no'=>$orderNo))->find();
        $payFee = $data['pay_fee'];

        $goods = $this->getOrderBody($orderNo);

        $order['body'] = $goods['name'];
        $order['order_no'] = $orderNo;
        $order['price'] = $payFee;
        $WxJsAPI = new WxJsAPIController();
        return $WxJsAPI->pay($order);
    }

    /**
     * 获取订单支付的介绍
     * @param $orderNo
     * @return array
     */
    private function getOrderBody($orderNo)
    {
        $data = M('goods_order_child')->where(array('order_no'=>$orderNo))->find();
        //商品信息
        $Goods = new GoodsModel();
        return $Goods->getGoodsInfo($data['gid']);
    }

    /**
     * 获取订单列表
     * @param string $state
     * @return array|mixed
     */
    public function getOrderList($state = 'all')
    {
        $maps['uid'] = $this->uid;
        $state == 'all' ? $maps['state'] = array('NEQ',0) : $maps['state'] = $state;

        $list = $this->where($maps)->order(array('add_time'=>'desc'))->select();

        if (is_array($list) && count($list) > 0) {
            $count = count($list);
            for ($i = 0; $i < $count; $i++) {
                $childList = $this->getOrderGoodsList($list[$i]['order_no']);
                $list[$i]['child_list'] = $childList;
            }
            return $list;
        }

        return array();
    }

    public function updateOrderState($orderNo, $state)
    {
        return $this->where(array('order_no'=>$orderNo))->data(array('state'=>$state))->save();
    }
}